package dev.blogmoon.cn.admin.aspect;

import cn.hutool.core.util.ReflectUtil;
import dev.blogmoon.cn.common.aspect.Dict;
import dev.blogmoon.cn.common.entity.Result;
import dev.blogmoon.cn.system.repository.SysDictRepository;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;

@Aspect
@Component
public class DictAspect {

    @Autowired
    private SysDictRepository dictRepository;

    @Pointcut("execution(* dev.blogmoon.cn.*.controller..*(..))")
    public void point() {
    }


    @Around("point()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object object = joinPoint.proceed();
        if (!(object instanceof Result)) {
            return object;
        }
        Result result = (Result) object;
        Object respObject = result.getData();
        if (respObject instanceof Collection) {
            Collection collection = (Collection) respObject;
            for (Object data : collection) {
                setDictFiled(data);
            }
            return result;
        }
        setDictFiled(respObject);
        return result;
    }

    private void setDictFiled(Object data) {
        if (null == data) {
            return;
        }
        Field[] fields = ReflectUtil.getFields(data.getClass());
        for (Field field : fields) {
            Dict dict = field.getAnnotation(Dict.class);
            if (null == dict) {
                continue;
            }
            String dictValue = dictRepository.getDictValue(dict.value(), ReflectUtil.getFieldValue(data, field));
            ReflectUtil.setFieldValue(data, field.getName() + "Label", dictValue);
        }
    }

}
